<template>
  <div>
    <div class="geren_zhu">
      <el-card class="box-card zhiliao" v-if="flag == 1">
        <div slot="header" class="clearfix">
          <span>个人资料</span>
          <el-button v-if="flag == 0" style="float: right; padding: 3px 0" type="text"
            >返回</el-button
          >
        </div>
        <table class="table-a">
          <tr>
            <td>头像</td>
            <td>
              <img
                referrer="no-referrer|origin|unsafe-url"
                class="layui-nav-img user_img"
                style="width:64px;height:64px"
                :src="this.$store.getters.getUser.avatar"
                fit="fill"
              />
            </td>
          </tr>
          <tr>
            <td>性别</td>
            <td>{{ this.userInfo.userSex == 1 ? "男" : "女" }}</td>
          </tr>
          <tr>
            <td>用户名</td>
            <td>{{ this.userInfo.username }}</td>
          </tr>

          <tr>
            <td>个性签名</td>
            <td>{{ this.userInfo.description }}</td>
          </tr>
        </table>

        <el-button class="geren_btn" type="button" @click="bianji"
          >编辑</el-button
        >
      </el-card>
      <el-card class="box-card zhiliao" v-else>
        <div slot="header" class="clearfix">
          <span>资料设置</span>
          <el-button @click.native="flag=1" style="float: right; padding: 3px 0" type="text"
            >返回</el-button
          >
        </div>

        <table class="table-a">
          <tr>
            <td>头像</td>
            <td>
              <el-upload
                class="upload-demo"
                ref="upload"
                action="/"
                :on-change="uploadFile"
                :auto-upload="false"
                :show-file-list="false"
              >
                <img
                  referrer="no-referrer|origin|unsafe-url"
                  class="layui-nav-img user_img"
                  style="width:64px;height:64px"
                  :src="this.$store.getters.getUser.avatar"
                  fit="fill"
                />
                <div class="img_tou">
                  <i
                    style="color:#fff;  position: absolute;    margin-left: -15px;    margin-top: -38px;"
                    class=" el-icon-camera"
                  ></i>
                </div>

                <!-- <el-button slot="trigger" size="small" type="text"
                  >修改头像</el-button
                > -->
              </el-upload>
            </td>
          </tr>
          <tr>
            <td>性别</td>
            <td style="width:300px">
              <el-radio v-model="radio" label="1">男</el-radio>
              <el-radio v-model="radio" label="0">女</el-radio>
            </td>
          </tr>
          <tr>
            <td>用户名</td>
            <td>
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm "
                style=" margin-bottom: 0;margin-left: -82px "
              >
                <el-form-item prop="name">
                  <el-input
                    type="txt"
                    v-model="ruleForm.name"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-form>
            </td>
          </tr>

          <tr>
            <td>个性签名</td>
            <td>
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="textarea1"
              >
              </el-input>
            </td>
          </tr>
        </table>

        <el-button
          class="geren_btn"
          type="primary"
          @click.native="submitForm('ruleForm')"
          >保存</el-button
        >
      </el-card>
    </div>
  </div>
</template>

<script>
import Nav from "../../com/components/Common/Nav.vue";
import HeadNav from "../../com/components/Common/HeadNav.vue";
import { ByUser } from "../../network/API/login";
import caidan from "../../pages/User/caidan";
import axios from "axios";
export default {
  components: { Nav, HeadNav, caidan },
  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else if (value.length < 4 || value.length > 10) {
        return callback(new Error("用户名必须大于4位和小于11位"));
      } else {
        this.ifname(); //发请求是否注册
        setTimeout(() => {
          if (
            this.type_name == "404" &&
            this.ruleForm.name != this.userInfo.username
          ) {
            callback(new Error("该用户已被注册"));
          } else {
            callback();
          }
        }, 1000);
      }
    };
    return {
      type_name: "", //用户名是否注册
      flag: 1,
      file: "", //头像
      userInfo: "", //用户信息
      imgUrl: "", //头像本地地址
      radio: this.$store.getters.getUser.userSex, //性别
      input: "", //用户名
      textarea1: "",
      ruleForm: {
        name: "",
        txt: "",
      },
      rules: {
        name: [{ validator: checkName, trigger: "blur" }],
      },
    };
  },
  methods: {
    ifname() {
      //判断用户名是否注册
      this.ruleForm.type = 1;
      ByUser({ username: this.ruleForm.name })
        .then((res) => {
          ;
          this.type_name = res.code;
          ;
        })
        .catch(function(error) {})
        .then(function() {
          // always executed
        });
    },
    bianji() {
      this.flag = 2;
      this.textarea1 = this.userInfo.description;
      this.ruleForm.name = this.userInfo.username;
    },
    baocun() {
      this.flag = 1;
    },
    uploadFile(file) {
      this.imgUrl = file.raw; // 拿到文件的信息

      ;
      this.userInfo.avatar = URL.createObjectURL(file.raw);
      this.$store.commit("SET_USERINFO", this.userInfo);

      let formdata = new FormData();
      formdata.append("userId", this.userInfo.userId);
      formdata.append("file", this.imgUrl);
      axios //修改头像
        .post("/fl-user/changeUserAvatar", formdata, {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          ;
          // this.type.type_name = res.data.code;

          // this.$router.go(0);
          if (res.data.code == 200) {
            this.$message("头像修改成功");
          } else {
            this.$message("头像修改失败");
          }
        })
        .catch(function(error) {});
    },

    submitForm(formName) {
      //修改用户名
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = new URLSearchParams();
          params.append("oldUsername", this.userInfo.username);
          params.append("newUsername", this.ruleForm.name);
          axios.post("/fl-user/changeUsername", params).then((res) => {
            if (res.data.code == 200) {
              this.userInfo.username = this.ruleForm.name;
            }
          });

        

          //修改个性签名
          let qm = new URLSearchParams();
          qm.append("userId", this.userInfo.userId);
          qm.append("desc", this.textarea1);
          axios.post("/fl-user/changeUserDesc", qm).then((res) => {
            ;
            this.userInfo.description = this.textarea1;
          });

          let xb = new URLSearchParams(); //选择性别
          xb.append("userId", this.userInfo.userId);
          xb.append("sex", parseInt(this.radio));
          axios.post("/fl-user/changeUserSex", xb, {}).then((res) => {
            ;
            this.userInfo.userSex = this.radio;
          });
          ;
          setTimeout(
            () =>
              this.$store.commit("SET_USERINFO", this.userInfo), //更新缓存
            2000
          );
          this.$message("信息修改成功");
          this.userInfo = this.$store.getters.getUser;
          ;
          this.flag=1;
          // this.$router.go(0);
        }
      }); //刷新页面
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    ;
  },
};
</script>

<style>
.upload-demo :hover .img_tou {
  width: 65px;
  height: 65px;
  background: rgba(0, 0, 0, 0.438);
  position: absolute;
  border-radius: 40px;
  top: 78px;
  left: 588px;
}
.upload-demo :hover .img_tou i {
}
.geren_zhu {
  width: 60%;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card .zhiliao {
  width: 60%;
}
.zhiliao {
  width: 100%;
}
.table-a {
  margin-left: 20%;
  text-align: left;
  font-size: 20px;
}
.table-a tr td {
  padding: auto;
  width: 150px;
  height: 80px;
}
.table-a .layui-nav-img .user_img {
  width: 60px;
  height: 60px;
}
.geren_btn {
  width: 100px;
  margin-top: 30px;
  margin-left: 45%;
  margin-bottom: 45px;
}

/* 头像上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
